<?php
$this->breadcrumbs = array(
	'材料价格查询'
);
?>
<div id="material-price-check-container" style="width: 960px;height: 600px;"></div>

<?php
$materialSearchUrl = CJSON::encode(
	Yii::app()->getController()->createUrl('material/search'));
$modelSearchUrl = CJSON::encode(
	Yii::app()->getController()->createUrl('materialModel/search'));
$priceSearchUrl = CJSON::encode(
	Yii::app()->getController()->createUrl('materialStatistic/priceCheck'));
$js = <<<EOF
Ext.define('Material', {
	extend : 'Ext.data.Model',
	fields : [ 'id', 'name', 'altNames', 'category' ]
});

Ext.define('MaterialModel', {
	extend : 'Ext.data.Model',
	fields : [ 'id', 'materialId', 'model', 'code', 'unit', 'referenceCode',
			'note' ]
});
Ext.onReady(function(){setTimeout(function(){
	var panel,materialStore,filter,materialGrid,modelStore,modelGrid,resultTabPanel;
	var filterTriggerClick = function(trigger) {
		materialStore.load({
			params : {
				query : filter.getValue()
			}
		});
	};
	filter = Ext.widget('trigger', {
		'triggerCls' : 'x-form-search-trigger',
		'onTriggerClick' : filterTriggerClick,
		width : 290,
		'listeners' : {
			specialkey : function(field, e) {
				if (e.getKey() == e.ENTER) {
					filterTriggerClick();
				}
			}
		}
	});
	materialStore = new Ext.data.Store({
		model : 'Material',
		pageSize : 12,
		proxy : {
			type : 'ajax',
			url : $materialSearchUrl,
			reader : {
				type : 'json',
				root : 'data'
			}
		}
	});
	materialStore.on('beforeload', function(store, operation,
			options) {
		Ext.apply(store.proxy.extraParams, {
			query : filter.getValue()
		});
	});
	materialGrid = Ext.widget('grid', {
		flex: 5,
		store : materialStore,
		columns : [ {
			header : '名称',
			dataIndex : 'name',
			sortable : false,
			flex : 5
		}, {
			header : '其它名称',
			dataIndex : 'altNames',
			sortable : false,
			flex : 2
		}, {
			header : '类别',
			dataIndex : 'category',
			sortable : false,
			flex : 3
		} ],
		dockedItems : [ {
			xtype : 'pagingtoolbar',
			store : materialStore,
			dock : 'bottom',
			displayInfo : true,
			beforePageText:'',
			afterPageText: '/{0}',
			displayMsg: '{0} - {1} / {2}'
		}, {
			xtype : 'toolbar',
			dock : 'top',
			items : [ filter ],
		} ],
	});
	modelStore = new Ext.data.Store({
		model : 'MaterialModel',
		pageSize : 7,
		proxy : {
			type : 'ajax',
			url : $modelSearchUrl,
			reader : {
				type : 'json',
				root : 'data'
			}
		}
	});
	var modelStoreBeforeload = function(store, operation, options) {
		var selection = materialGrid.getSelectionModel()
				.getSelection();
		var materialId = selection && selection[0] ? selection[0]
				.get('id') : 0;
		Ext.apply(store.proxy.extraParams, {
			materialId : materialId
		});
	};
	modelStore.on('beforeload', modelStoreBeforeload);
	modelGrid = Ext.widget('grid', {
		flex : 3,
		store : modelStore,
		columns : [ {
			header : '型号',
			dataIndex : 'model',
			sortable : false,
			flex : 1
		}, {
			header : '单位',
			dataIndex : 'unit',
			sortable : false,
			flex : 1
		}, {
			header : '清单代码',
			dataIndex : 'code',
			sortable : false,
			flex : 1
		}, {
			header : '类别',
			dataIndex : 'referenceCode',
			sortable : false,
			flex : 1
		}, {
			header : '备注',
			dataIndex : 'note',
			sortable : false,
			flex : 1
		} ],
		dockedItems : [ {
			xtype : 'pagingtoolbar',
			store : modelStore,
			dock : 'bottom',
			displayInfo : true,
			beforePageText:'',
			afterPageText: '/{0}',
			displayMsg: '{0} - {1} / {2}'
		} ],
	});
	materialGrid.on('selectionchange', function(view, selections,
			options) {
		modelStore.load();
	});
	var currentTabs=new Ext.util.MixedCollection();
	var createMaterialPricePanel=function(data){
		var chart, grid;
		var materialModel=data.materialModel;
		if(currentTabs.containsKey(materialModel.id)){
			resultTabPanel.setActiveTab(currentTabs.get(materialModel.id));
			return;
		}
		var count = resultTabPanel.items.length;
		grid=Ext.widget('grid', {
			title: '历史价格',
	        flex: 4,
			store: Ext.create('Ext.data.ArrayStore', {
	            	data: data.recentPrices,
	            	fields: [{
	            		name: 'date',
	            		mapping: 'date',
	            		type: 'date',
	            		dateFormat: 'Y-m-d',
	            		sortType: 'asDate'
					},{
						name: 'price',
						mapping: 'price',
						type:'float'
					}],
					
				}),
			columns: [{
				text: '日期',
				dataIndex: 'date',
				renderer: function(value) {
					return Ext.Date.format(value, "Y-m-d");
				}
			},{
				text: '单价 （元/'+materialModel.unit+'）',
				dataIndex: 'price',
				renderer: function(value) {
					return Ext.Number.toFixed(value, 2);
				},
				flex: 1
			}]
		});
		if(data.recentPrices.length>1){
			chart = Ext.create('Ext.chart.Chart', {
				title: '价格曲线',
	            style: 'background:#fff',
	            height:250,
	            animate: true,
	            store: Ext.create('Ext.data.ArrayStore', {
	            	data: data.recentPrices,
	            	fields: [{
	            		name: 'date',
	            		mapping: 'date',
	            		type: 'date',
	            		dateFormat: 'Y-m-d',
	            		sortType: 'asDate'
						},{
						name: 'price',
						mapping: 'price',
						type:'float'
						}],
				}),
	            shadow: true,
	            theme: 'Category1',
	            legend: {
	                position: 'right'
	            },
	            axes: [{
	                type: 'Numeric',
	                minimum: 0,
	                position: 'left',
	                fields: ['price'],
	                title: '价格',
	                minorTickSteps: 1,
	                grid: {
	                    odd: {
	                        opacity: 1,
	                        fill: '#ddd',
	                        stroke: '#bbb',
	                        'stroke-width': 0.5
	                    }
	                }
	            }, {
	                type: 'Time',
	                position: 'bottom',
	                fields: ['date'],
	                title: '日期',
	                dateFormat: 'Y-m-d',
	                label: {
			            rotate: {
			                degrees: 315
			            }
			        }
	            }],
	            series: [{
	                type: 'line',
	                highlight: {
	                    size: 7,
	                    radius: 7
	                },
	                axis: 'left',
	                xField: 'date',
	                yField: 'price',
	                markerConfig: {
	                    type: 'cross',
	                    size: 4,
	                    radius: 4,
	                    'stroke-width': 0
	                },
	                tips: {
	                    trackMouse: true,
	                    width: 180,
	                    height: 34,
	                    layout: 'fit',
	                    items:[{
	                    	html: 'test'
	                    }],
	                    renderer: function(data, item) {
	                    	var storeItem=item.storeItem;
	                    	if(this.items.get(0).rendered){
	                        	this.items.get(0).el.dom.innerHTML=Ext.Date.format(storeItem.get('date'), "Y年m月d日")+'： '
	                        	+Ext.Number.toFixed(storeItem.get('price'), 2)+'/'+materialModel.unit;
	                        }else{
	                        	this.items.get(0).html=Ext.Date.format(storeItem.get('date'), "Y年m月d日")+'： '
	                        	+Ext.Number.toFixed(storeItem.get('price'), 2)+'/'+materialModel.unit;
	                        }
	                    }
	                }
	            }]
	        });
	        chart.store.sort([
			    {
			        property : 'date',
			        direction: 'ASC'
			    }
			]);
		}else{
			chart=Ext.widget('panel',{
				height:250,
				html:'数据太少，无法绘制图形'
			});
		}
		var tab = resultTabPanel.add({
            title: materialModel.material.name + (materialModel.model?' ' + materialModel.model:''),
            closable: true,
            layout: {
				type: 'vbox',
				align : 'stretch',
				pack  : 'start'
			},
			items:[
				grid,
				chart
			]
        });
        tab.on('close', function(){
        	currentTabs.remove(tab);
        	console.log(currentTabs);
		});
        tab.doComponentLayout();
        resultTabPanel.setActiveTab(tab);
        currentTabs.add(materialModel.id,tab);
	};
	modelGrid.on('selectionchange', function(view, selections,
			options) {
		if(selections.length>0){
			var selectedModel=selections[0];
			var materialModelId=selectedModel.get('id');
			jQuery.get($priceSearchUrl, {materialModelId:materialModelId},function(data, textStatus, jqXHR){
				createMaterialPricePanel(data);
			});
		}
	});
	resultTabPanel=Ext.widget('tabpanel',{
		region: 'center'
	});
	panel=Ext.widget('panel', {
	    title: '材料价格查询',
	    width: 960,
	    height: 600,
	    layout: {
	        type: 'border'
    	},
	    items: [{
	    	region:'west',
	    	width: 320,
	    	layout: {
				type: 'vbox',
				align : 'stretch',
				pack  : 'start',
			},
			items: [
			    materialGrid,
			    modelGrid
			]
	    }, resultTabPanel],
	    renderTo: Ext.get('material-price-check-container')
	});
	setTimeout(function(){materialStore.load();},1000);
},1000);});
EOF
;
Yii::app()->clientScript->registerScript('dynamic-material-price-view', $js, CClientScript::POS_HEAD);

?>